# coding=utf-8
import time
import uuid

from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from wechatpy.oauth import WeChatOAuth
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import redirect
from fe_api.user import forms
from fe_api.user.utils import view_funcs

from django.contrib import auth
from wechatpy import WeChatClient


# wechat_login = WeixinLogin(settings.APPID, settings.APPSECRET)

redirect_uri = settings.MP_REDIRECT_URI
mp = WeChatOAuth(app_id=settings.APPID, secret=settings.APPSECRET,
                 redirect_uri=redirect_uri, scope='snsapi_userinfo')
wechat_client = WeChatClient(settings.APPID, settings.APPSECRET)


class Login(APIView):

    """
    应该还有注册的逻辑
    """

    authentication_classes = (SessionAuthentication,)
    permission_classes = (AllowAny,)

    def get(self, request):
        url = mp.authorize_url
        content = {
            "url": url,
        }
        return Response(content)


class Authorization(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (AllowAny,)

    def get(self, request):
        code = request.GET.get("code")
        data = mp.fetch_access_token(code)
        print("data: ", data)
        # ticket = js_api_client.get_jsapi_ticket()
        # print("ticket: ", ticket)
        content = {
            "data": data,
        }
        user = view_funcs.get_or_create_user(data["openid"])
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        return Response(content)
        # username = 'admin'
        # password = 'admin'
        # user = auth.authenticate(
        #     username=username, password=password)
        # if user is not None and user.is_active:
        #     auth.login(request, user)
        # return Response({
        #     'status': 200})


class JSAPISignature(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        url = request.data.get("url")
        if not url:
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        ticket = wechat_client.jsapi.get_jsapi_ticket()
        timestamp = int(time.time())
        noncestr = uuid.uuid1().hex
        sign = wechat_client.jsapi.get_jsapi_signature(
            noncestr, ticket, timestamp, url)
        return Response({
            "status": 200,
            "msg": "success",
            "data": {
                "appid": settings.APPID,
                "sign": sign,
                "timestamp": timestamp,
                "noncestr": noncestr,
            },
        })


class UserInfo(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        """
        获取个人信息
        """
        info = view_funcs.get_user_info(request.user)
        return Response({
            "status": 200,
            "msg": "success",
            "data": info,
        })


class UserAddressList(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        """
        获取用户地址列表
        """
        address_list = view_funcs.get_user_address_list(request.user)
        return Response({
            "status": 200,
            "msg": "success",
            "data": address_list,
        })

    def post(self, request):
        """
        添加用户地址
        """
        form = forms.CreateUserAddress(request.data)
        if not form.is_valid():
            return Response({
                "status": 400,
                "msg": "parameter error"
            })

        address = form.cleaned_data.get("address")
        contact = form.cleaned_data.get("contact")
        phone = form.cleaned_data.get("phone")

        view_funcs.create_user_address(request.user, address, contact, phone)
        return Response({
            "status": 200,
            "msg": "success",
        })


class UserAddressDefault(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def put(self, request, address_id):
        """
        设置地址为默认
        """
        view_funcs.update_default_address(request.user, address_id)
        return Response({
            "status": 200,
            "msg": "success",
        })


class UserAddressDetail(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def delete(self, request, address_id):
        """
        删除地址
        """
        view_funcs.delete_user_address(request.user, address_id)
        return Response({
            "status": 200,
            "msg": "success",
        })


class StarSutraEdition(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def put(self, request, sutra_edition_id):
        """
        收藏经书版本
        """
        view_funcs.star_sutra_edition(request.user, sutra_edition_id)
        return Response({
            "status": 200,
            "msg": "success",
        })

    def delete(self, request, sutra_edition_id):
        """
        取消收藏经书版本
        """
        view_funcs.unstar_sutra_edition(request.user, sutra_edition_id)
        return Response({
            "status": 200,
            "msg": "success",
        })


class StarSutraEditionList(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        """
        获取用户收藏经书列表
        """
        form = forms.GetStarredSutraEditionList(request.query_params)
        if not form.is_valid():
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        data = form.cleaned_data
        starred_list = view_funcs.get_starred_sutra_edition_list(
            request.user, data["limit"], data["offset"])
        return Response({
            "status": 200,
            "msg": "success",
            "data": starred_list,
        })
